﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WanMeiCommon
{
    /// <summary>
    /// 从数据读取的数据转化为业务实体模型类
    /// DataTable=>Model
    /// </summary>
    public class DataMapper
    {
        /// <summary>
        /// 单模型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T Entity<T>(DataTable dt)
        {
            T _entity = Activator.CreateInstance<T>();
            List<PropertyInfo> pis = typeof(T).GetProperties().ToList();
            pis.ForEach((pi) =>
            {
                if (!DBNull.Value.Equals(dt.Rows[0][pi.Name]))
                {
                    pi.SetValue(_entity, Convert.ChangeType(dt.Rows[0][pi.Name], pi.PropertyType));
                }
            });
            return _entity;
        }
        /// <summary>
        /// 集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> EnityList<T>(DataTable dt)
        {
            List<T> res = new List<T>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                T _entity = Activator.CreateInstance<T>();
                List<PropertyInfo> pis = typeof(T).GetProperties().ToList();
                pis.ForEach((pi) =>
                {
                    if (!DBNull.Value.Equals(dt.Rows[i][pi.Name]))
                    {
                        pi.SetValue(_entity, Convert.ChangeType(dt.Rows[0][pi.Name], pi.PropertyType));
                    }
                });
                res.Add(_entity);
            }
            return res;
        }
    }
}
